package com.vs.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.vs.dao.DocumentOperation;
import com.vs.model.DocSearchForm;
import com.vs.util.Constants;

/**
 * Servlet implementation class DocDownloader
 */
public class DocDownloader extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public DocDownloader() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		Integer docId = Integer.parseInt(request.getParameter("docId"));
//		System.out.println("docId=" + docId);
		Constants.log.debug("DocDownloader doGet docId=" + docId);

		PrintWriter out = new PrintWriter(response.getWriter());

		DocSearchForm doc = new DocumentOperation().getDocInfo(docId);
		String filename = doc.getFileName();
		String filepath = doc.getFilePath();

		// System.out.println("download filename="+filepath + filename);

		// filepath.replaceAll("\\", "\\\\");
		response.setContentType("APPLICATION/OCTET-STREAM");
		response.setHeader("Content-Disposition", "attachment; filename=\""
				+ filename + "\"");

		Constants.log.debug("download filename=" + filepath);
		java.io.FileInputStream fileInputStream = new java.io.FileInputStream(
				filepath);

		int i;
		while ((i = fileInputStream.read()) != -1) {
			out.write(i);
		}
		fileInputStream.close();

	}

}
